//
//  HWSubscribeViewController.m
//  HuaiWu
//
//  Created by HuaiWu  on 2022.
//  Copyright © 2022 HuaiWu . All rights reserved.
//

#import "HWSubscribeViewController.h"

#import "HWRightsInterestsCell.h"
#import "HWSubscribeDesCell.h"
#import "HWSubscribeButtonCell.h"
#import "HWOtherButtonCell.h"
#import "HWTrialSwitchCell.h"

@interface HWSubscribeViewController ()

@property (nonatomic,copy) NSString *currentProId;
@property (nonatomic,assign) BOOL isOn;

@end

@implementation HWSubscribeViewController

- (void)viewDidLoad {

    [super viewDidLoad];
    _isOn = YES;
    // Do any additional setup after loading the view from its nib.
    self.leftItem.hidden = YES;
    [self addBackImageView];
    //[self setLeftItemWithTitle:@"恢复购买" selector:@selector(resumePurchase:)];
    [self setRightItemWithIcon:[UIImage imageNamed:@"dy_close"] selector:@selector(closeButtonAction:)];
    
    //进入售卖页 打点
    [kRequestManager saveRequestWithKey:@"sellpage" success:^(id responseObject) {
        
    } failure:^(NSString *errorMsg) {
        
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HWRightsInterestsCell" bundle:nil] forCellReuseIdentifier:@"HWRightsInterestsCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HWSubscribeDesCell" bundle:nil] forCellReuseIdentifier:@"HWSubscribeDesCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HWSubscribeButtonCell" bundle:nil] forCellReuseIdentifier:@"HWSubscribeButtonCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HWOtherButtonCell" bundle:nil] forCellReuseIdentifier:@"HWOtherButtonCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HWTrialSwitchCell" bundle:nil] forCellReuseIdentifier:@"HWTrialSwitchCell"];

    self.tableView.frame = CGRectMake(0,-self.statusBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height + self.statusBarHeight);
    [self.view bringSubviewToFront:self.navigationBar];
    [self requestData];
    
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstEnter"] boolValue]) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"YES" forKey:@"isFirstEnter"];
        [userDefaults synchronize];
    }
}

- (void)addBackImageView {
    UIImage *image = [UIImage imageNamed:@"dy_bg"];
    
    float width = kScreenWidth;
    float height = width * image.size.height / image.size.width;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, width, height)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.clipsToBounds = true;
    imageView.image = image;
    [self.view addSubview:imageView];
    [self.view sendSubviewToBack:imageView];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIView *)ittemLeftItemWithTitle:(NSString *)title selector:(SEL)selector {
    UIView *item;
    if (title.length == 0) {
        item = [UIView new];
        return item;
    }
    
    if (!self.leftItem) {
        self.leftItem = [UIView new];
    }
    self.leftItem.backgroundColor = [UIColor clearColor];
    
    // 移除之前的子控件
    [self.leftItem.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor clearColor];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    if (selector) {
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    }
    [btn setTitle:[NSString stringWithFormat:@"%@",title] forState:UIControlStateNormal];
    [btn setTitle:[NSString stringWithFormat:@"%@",title] forState:UIControlStateHighlighted];
    [btn setTitleColor:UIColorFromHex(0xFFFFFF) forState:UIControlStateNormal];
    [btn setTitleColor:UIColorFromHex(0xFFFFFF) forState:UIControlStateHighlighted];
    [btn setBackgroundColor:UIColorFromHexA(0xFFFFFF,0.23)];
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    btn.layer.borderColor = UIColorFromHex(0xFFFFFF).CGColor;
    btn.layer.borderWidth = 1.0;
    float leight = 80;

    self.leftItem.frame = CGRectMake(20, self.statusBarHeight, leight, self.navigationBar.frame.size.height - self.statusBarHeight);
    btn.frame = CGRectMake(0, self.leftItem.frame.size.height/2 - 24/2, self.leftItem.frame.size.width, 24);
    [self.leftItem addSubview:btn];
    return self.leftItem;
}

- (void)requestData {
    self.requestStates = 2;
    [self refreshData];
}

#pragma mark - cellDataSource

- (NSArray *)cellDataSource {
    
    if (!self.dataSource) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
        
        __block NSMutableArray *subarr = nil;
        __block NSDictionary *dict = nil;
                
        float height = kScreenWidth*460/375;

        //vip 权益
        subarr = [NSMutableArray arrayWithCapacity:1];

        dict =  @{@"class":HWRightsInterestsCell.class,
                  @"height":@([HWRightsInterestsCell getCellFrame:[NSNumber numberWithFloat:height]])};
        [subarr addObject:dict];
                
//        dict =  @{@"class":HWSubscribeDesCell.class,
//                  @"height":@([HWSubscribeDesCell getCellFrame:[HWSubscribeDesCellModel ittemModelWithTime:@"解锁全部高级功能\n100%无广告" time2:@"" time3:@"" font:24]]),
//                  @"data":[HWSubscribeDesCellModel ittemModelWithTime:@"解锁全部高级功能\n100%无广告" time2:@"" time3:@"" font:24]};
//        [subarr addObject:dict];
        
        dict =  @{@"class":HWSubscribeDesCell.class,
                  @"height":@([HWSubscribeDesCell getCellFrame:[HWSubscribeDesCellModel ittemModelWithTime:@"解锁全部高级功能，可无限次使用乐器调音，支持吉他、尤克里里、二胡、其他调音器，免费试用3天，可自动续订，续费" time2:@"￥298/年" time3:@"，免费享受后续功能迭代，无需额外付费，随时取消" font:15]]),
                  @"data":[HWSubscribeDesCellModel ittemModelWithTime:@"解锁全部高级功能，可无限次使用乐器调音，支持吉他、尤克里里、二胡、其他调音器，免费试用3天，可自动续订，续费" time2:@"￥298/年" time3:@"，免费享受后续功能迭代，无需额外付费，随时取消" font:15]};
        [subarr addObject:dict];
        
//        dict =  @{@"class":HWSubscribeDesCell.class,
//                  @"height":@([HWSubscribeDesCell getCellFrame:[HWSubscribeDesCellModel ittemModelWithTime:@"带有免费试用期的订阅将自动续订为付费订阅，除非关闭自动续订。在确认购买时，将向iTunes账户收取费用。订阅将自动续订，除非您在当前订阅期结束前至少提前24小时关闭自动续订。在当前订阅期结束前24小时内将向账户收取续订费用，并确认续订费用。用户可以管理订阅。购买后可前往用户账户设置来关闭自动续订。" time2:@"" time3:@"" font:10]]),
//                  @"data":[HWSubscribeDesCellModel ittemModelWithTime:@"带有免费试用期的订阅将自动续订为付费订阅，除非关闭自动续订。在确认购买时，将向iTunes账户收取费用。订阅将自动续订，除非您在当前订阅期结束前至少提前24小时关闭自动续订。在当前订阅期结束前24小时内将向账户收取续订费用，并确认续订费用。用户可以管理订阅。购买后可前往用户账户设置来关闭自动续订。" time2:@"" time3:@"" font:10]};
//        [subarr addObject:dict];
        
        dict =  @{@"class":HWTrialSwitchCell.class,
                  @"height":@([HWTrialSwitchCell getCellFrame:[NSNumber numberWithFloat:90]]),
                  @"data":[HWTrialSwitchCellModel ittemModelWithTitle:_isOn ? @"已开启免费订阅" : @"开启免费订阅" isOn:_isOn],
                  @"delegate":@YES};
        [subarr addObject:dict];
                
        NSString *title1 = @"按年订阅 ￥298";
                
        if (_isOn) {
            title1 = @"继续试用";
        }
        
        dict =  @{@"class":HWSubscribeButtonCell.class,
                  @"height":@([HWSubscribeButtonCell getCellFrame:[NSNumber numberWithFloat:100]]),
                  @"data":[HWSubscribeButtonCellModel ittemModelWithTitle:title1],
                  @"delegate":@YES};
        [subarr addObject:dict];
        
        dict =  @{@"class":HWOtherButtonCell.class,
                  @"height":@([HWOtherButtonCell getCellFrame:[NSNumber numberWithFloat:40]]),
                  @"delegate":@YES};
        [subarr addObject:dict];

        [arr addObject:subarr];
        
        self.dataSource = arr;
    }
    return self.dataSource;
}

#pragma mark HWTrialSwitchCellDelegate 开关

- (void)trialSwitchCell:(HWTrialSwitchCell *)cell isOn:(BOOL)isOn {
    _isOn = !_isOn;
    [self refreshData];
}

#pragma mark ECSubscribeButtonCellDelegate 订阅

- (void)subscribeButtonCell:(HWSubscribeButtonCell *)cell button:(UIButton *)sender {
    if (kAppDelegate.netStatus == NotReachable) {
        [self showProgressHUD:@"未检测到网络，请检查网络设置或者在设置中打开允许APP使用网络的权限"];
        return;
    }
    
    _currentProId = kSubscribeId;
    if (_isOn) {
        _currentProId = kFreeTrialSubscribeId;
    }

    if (sender.tag == 10) {
        
        [SVProgressHUD showWithStatus:@"正在加载中，请稍后..."];
        
        [kIAPHelper startPurchaseWithProductId:_currentProId completeHandle:^(IAPPurchType type, NSDictionary *dict) {
            if (type == IAPPurchVerSuccess || type == IAPPurchSuccess) {
                
                [SVProgressHUD dismiss];
                
                UserManager *userManager = kUserManager.userManager;

                userManager.isSubscribe = YES;

                [userManager saveUserData:userManager];
        
                
                // 3.GCD
                dispatch_async(dispatch_get_main_queue(), ^{
                   // UI更新代码
                    //关闭
                    [self dismissViewControllerAnimated:YES completion:nil];
                    
                    if (_type == 1) {
                        
                    } else {
                        kAppDelegate.isClose = YES;
                        [kApplicationManager setupWindow:kAppDelegate.window];
                    }
                });
                
            } else {
               [SVProgressHUD dismiss];
                
                // 3.GCD
                dispatch_async(dispatch_get_main_queue(), ^{
                   // UI更新代码
                    
                     if (type == IAPPurchRestoreFailed || type == IAPPurchRestoreNotBuy) {

                     } else if (type == IAPPurchCancle) {
                         [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOW_AD_NOTIFICATION" object:nil userInfo:nil];
                     }
                });
            }
        }];
    }
}

#pragma mark HWOtherButtonCellDelegate 服务条款 隐私政策 恢复购买

- (void)otherButtonCell:(HWOtherButtonCell *)cell button:(UIButton *)sender {
    if (sender.tag == 20) {
        [self gotoBaseWebViewController:sender.titleLabel.text url:@""];
    } else if (sender.tag == 21) {
        [self gotoBaseWebViewController:sender.titleLabel.text url:@""];
    } else if (sender.tag == 22) {
        [self resumePurchase:sender];
    }
}

#pragma mark - Action

//恢复购买
- (void)resumePurchase:(UIButton *)button {
    if (kAppDelegate.netStatus == NotReachable) {
        [self showProgressHUD:@"未检测到网络，请检查网络设置或者在设置中打开允许APP使用网络的权限"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"恢复中..."];
    //恢复
    [kIAPHelper restorePurchasesWithCompleteHandle:^(IAPPurchType type, NSDictionary *dict) {
        if (type == IAPPurchVerSuccess || type == IAPPurchSuccess) {
            
            [SVProgressHUD dismiss];
            
            UserManager *userManager = kUserManager.userManager;
            
            userManager.isSubscribe = YES;

            [userManager saveUserData:userManager];
    
            // 3.GCD
            dispatch_async(dispatch_get_main_queue(), ^{
               // UI更新代码
                //关闭
                [self dismissViewControllerAnimated:YES completion:nil];
                
                if (_type == 1) {
                    
                } else {
                    kAppDelegate.isClose = YES;
                    [kApplicationManager setupWindow:kAppDelegate.window];
                }
            });

        } else {
           [SVProgressHUD dismiss];
        }
    }];
}

- (void)closeButtonAction:(UIButton *)button {
    //关闭
    [self dismissViewControllerAnimated:YES completion:^{
        if (!kUserManager.userManager.isSubscribe) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOW_AD_NOTIFICATION" object:nil userInfo:nil];
        }
    }];
    
    if (_type == 1) {
        
    } else {
        kAppDelegate.isClose = YES;
        [kApplicationManager setupWindow:kAppDelegate.window];
    }
}

@end

